/*
 * calibration.c
 *
 * Created: 10/05/2012 23:33:17
 *  Author: Alex
 */ 

// Calibration of the weight scale.

#include <avr/io.h>
#define F_CPU 8000000
#include <util/delay.h>
#include <stdio.h> 
#include "weight_sensor.h"
#include "lcd162.h"
#include "switch.h"
#include "uart.h"
#include "calibration.h"
#include "eeprom.h"

// enter calibration mode timeout, in tenths of second (approx)
#define CALIBRATION_TIMEOUT 30

void Calibration();
void CalibrationEnter();

void CalibrationEnter()
{
		LCDClear();
		LCDDispString("Press S3 to");
		LCDGotoXY(0,1);
		LCDDispString("calibrate.");
		for (uint8_t i = CALIBRATION_TIMEOUT; (( i > 0) & (S3() == 0)); i--)
		{
			LCDGotoXY(11,1);
			LCDDispInteger(i/10);
			LCDDispString("  ");
			_delay_ms(100);
		}
		if (S3())
		{
			Calibration();
		}
}

void Calibration()
{
	uint16_t temp;
	char str[6] = {'\0'};
	uint8_t i;
	
	LCDClear();
	LCDDispString("Calibration Mode");
	LCDGotoXY(0,1);
	LCDDispString("Use UART");
	_delay_ms(1500);
		
	/**********
	* STEP 1
	**********/
	// No load.
	// Press button (S3).
	UARTSendString("No weight. Press S3 to save.");
	UARTSendChar('\r');
	while (S3() == 0)
	{
		LCDClear();
		LCDDispInteger(WeightNoCalibrated());
		_delay_ms(100);
	}

	// Read ADC
	temp = WeightNoCalibrated();
	
	// Save data to EEPROM.
	EEPROMWrite(ADDRESS_O, temp);
	
	UARTSendInteger(EEPROMRead(ADDRESS_O));
	UARTSendString("Data saved");
	UARTSendChar('\r');
	
	// Delay for preventing pressing the buttonn twice
	_delay_ms(1000);

	/**********
	* STEP 2
	**********/
	// Full load (or well-known load = 1 kg).
	// Press button (S3).

	UARTSendString("Full load. Press S3 to save.");
	UARTSendChar('\r');
	while (S3() == 0)
	{
		LCDClear();
		LCDDispInteger(WeightNoCalibrated());
		_delay_ms(100);
	}

	// Read ADC
	temp = WeightNoCalibrated();	
	EEPROMWrite(ADDRESS_F, temp);
	
	UARTSendInteger(EEPROMRead(ADDRESS_F));
	UARTSendString("Data saved");
	UARTSendChar('\r');
	
	/**********
	* STEP 3
	**********/
	// Receive the weight
	UARTSendString("Send weight in grams + space");
	
	i = 0;
	str[i] = UARTReadChar();
	while ((str[i] != 32)&(i < 6)) // 32 = space
	{
		i++;
		str[i] = UARTReadChar();
	}
	str[i] = 0;
	sscanf(str,"%u ", &temp);
	
	EEPROMWrite(ADDRESS_W, temp);
	
	UARTSendInteger(EEPROMRead(ADDRESS_W));
	UARTSendChar('\r');
	
	UARTSendString("Calibration done");
	//WeightDataUpdate();
	_delay_ms(2000);	
}





